package com.qiaoba.module.system.controller;

import com.github.pagehelper.PageHelper;
import com.qiaoba.api.log.annotation.Log;
import com.qiaoba.api.log.enums.BusinessType;
import com.qiaoba.api.system.entity.vo.SysUserVO;
import com.qiaoba.common.base.entity.AjaxResult;
import com.qiaoba.common.database.entity.PageQuery;
import com.qiaoba.common.database.entity.PageResult;
import com.qiaoba.module.system.entity.param.SysUserRoleParam;
import com.qiaoba.module.system.service.SysUserRoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户角色管理 Web层
 *
 * @author ailanyin
 * @date 2023-09-12 20:41:22
 */
@Validated
@RestController
@RequestMapping("/system/role/auth-user")
@RequiredArgsConstructor
@Tag(name = "用户角色管理")
public class SysUserRoleController {

    private final SysUserRoleService sysUserRoleService;

    @PreAuthorize("hasAuthority('system:role:list')")
    @GetMapping("/allocated-list")
    @Operation(summary = "已绑定用户")
    public PageResult allocatedList(SysUserRoleParam param, PageQuery pageQuery) {
        PageHelper.startPage(pageQuery.getPageNum(), pageQuery.getPageSize());
        List<SysUserVO> list = sysUserRoleService.selectAllocatedList(param);
        return PageResult.build(list);
    }

    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PreAuthorize("hasAuthority('system:role:edit')")
    @PutMapping("/cancel-all")
    @Operation(summary = "解绑用户")
    public AjaxResult cancelAuthUser(@RequestParam("roleId") String roleId, @RequestParam("userIds") List<String> userIds) {
        sysUserRoleService.deleteByRoleIdAndUserIds(roleId, userIds);
        return AjaxResult.success();
    }

    @PreAuthorize("hasAuthority('system:role:list')")
    @GetMapping("/unallocated-list")
    @Operation(summary = "未绑定用户")
    public PageResult unallocatedList(SysUserRoleParam param, PageQuery pageQuery) {
        PageHelper.startPage(pageQuery.getPageNum(), pageQuery.getPageSize());
        List<SysUserVO> list = sysUserRoleService.selectUnallocatedList(param);
        return PageResult.build(list);
    }

    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PreAuthorize("hasAuthority('system:role:edit')")
    @PutMapping("/bind")
    @Operation(summary = "绑定用户")
    public AjaxResult insertAuthUsers(@RequestParam("roleId") String roleId, @RequestParam("userIds") List<String> userIds) {
        sysUserRoleService.insertAuthUsers(roleId, userIds);
        return AjaxResult.success();
    }

}
